/*
 * 天虹商场股份有限公司版权所有.
 */
package com.rainbow.hmkmybatis.result;

import com.mysql.cj.api.mysqla.result.Resultset;
import com.rainbow.hmkmybatis.config.Configuration;
import com.rainbow.hmkmybatis.config.MapperRegistory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * TODO
 *
 * @author 黄明坤
 * @version 1.0.0
 * @date 2020/6/28
 */
public class ResultSetHandler {

    private final Configuration configuration;

    public ResultSetHandler(Configuration configuration) {
        this.configuration = configuration;
    }


    /**
     *
     * @param pstmt 数据库查询结果
     * @param mapperData 类名+包名
     * @param <E>
     * @return
     * @throws Exception
     */
    public <E> E handle(PreparedStatement pstmt, MapperRegistory.MapperData mapperData) throws Exception{
        Object resultBean = new DefaultObjectFactory().create(mapperData.getType());
        ResultSet resultset = pstmt.getResultSet();
        if(resultset.next()){
            int i = 0;
            for (Field field : resultBean.getClass().getDeclaredFields()) {
                //根据类目将类的属性值注入到类对象中
                setValue(resultBean, field, resultset ,i);
            }
        }
        return (E) resultBean;
    }

    private void setValue(Object resultObj, Field field, ResultSet rs, int i) throws NoSuchMethodException, SQLException, InvocationTargetException, IllegalAccessException {
        Method setMethod = resultObj.getClass().getMethod("set" + upperCapital(field.getName()), field.getType());
        setMethod.invoke(resultObj, getResult(field,rs));
    }

    /**
     * 数据类型的转换
     * @param field
     * @param rs
     * @return
     * @throws SQLException
     */
    private Object getResult(Field field, ResultSet rs) throws SQLException {
        //TODO type handles
        Class<?> type = field.getType();
        if(Integer.class == type){
            return rs.getInt(field.getName());
        }
        if(String.class == type){
            return rs.getString(field.getName());
        }
        return rs.getString(field.getName());
    }

    /**
     * 获取类中的set方法
     * @param name
     * @return
     */
    private String upperCapital(String name) {
        String first = name.substring(0, 1);
        String tail = name.substring(1);
        return first.toUpperCase() + tail;
    }
}
